package com.bilibili.dubbo.api;

import com.bilibili.dubbo.api.mongo.VideoApi;
import com.bilibili.dubbo.utils.IdWorker;
import com.bilibili.model.mongo.Video;
import com.bilibili.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * @author HuangRongFu
 * 2021/11/28 星期日4:31 下午
 */

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 发布小视频
     *
     * @param pojo
     */
    @Override
    public void add(Video pojo) {

        //设置vid
        pojo.setVid(idWorker.getNextId("video"));

        //设置创建时间
        pojo.setCreated(System.currentTimeMillis());

        //添加到数据库
        mongoTemplate.insert(pojo);
    }

    /**
     * 通过vid查询小视频
     *
     * @param vidList
     * @return
     */
    @Override
    public List<Video> findByVids(List<Long> vidList) {

        Query query = new Query(Criteria.where("vid").in(vidList));

        return mongoTemplate.find(query, Video.class);

    }

    /**
     * 分页查询，按发布时间降序
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<Video> findPage(long page, Long pageSize) {

        Query query = new Query();

        //查询视频综述
        long total = mongoTemplate.count(query, Video.class);
        long start = (page -1) * pageSize;

        List<Video> videoList = new ArrayList<>();
        if (total > start){

            query.skip(start).limit(pageSize.intValue());
            query.with(Sort.by(Sort.Order.desc("created")));

            videoList = mongoTemplate.find(query, Video.class);
        }

        return new PageResult<Video>(page, pageSize, total, videoList);
    }
}
